//
//  HorizontalScrollMenu.m
//  MenuTest
//
//  Created by xinqing on 15/9/10.
//  Copyright (c) 2015年 Pansoft. All rights reserved.
//

#import "HorizontalScrollMenu.h"
#import "Constant.h"
#import "EnvironmentVariable.h"
#import "EFTagButton.h"
#import "EFMessageService.h"

#define MENU_HEIGHT 36
#define MENU_BUTTON_WIDTH  70
#define MIN_MENU_FONT  14.f
#define MAX_MENU_FONT  17.f

@implementation HorizontalScrollMenu {
    UIScrollView *_scrollView;
    UIButton *_currentSelectedButton;
    UIView *_titleBar;
    NSMutableArray *_buttons;
}

-(instancetype)initWithFrame:(CGRect)frame items:(NSMutableArray *)items {
    self = [super initWithFrame:frame];
    if(self) {
        //点击进入聊天列表之后二级菜单的同步
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(unreadcountRefresh:) name:unreadcountChange
                                                   object:nil];
        
        //收到消息之后的监听
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(unreadcountRefresh:) name:@"chatCountChange"
                                                   object:nil];
        //任务列表数据改变之后的二级菜单的同步
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(taskUnreadRefresh:) name:@"taskUnreadcountChange"
                                                   object:nil];
        
        //通讯录数据改变之后的二级菜单的同步(新的朋友，群通知)
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(chatAddressBookAction) name:@"chatAddressCountChange"
                                                   object:nil];
        //初始化property
        self.items= items;
        self.backgroundColor = EF_RED_COLOR;
        self.selectedTitleColor = [UIColor whiteColor];
        self.selectedFontSize = MAX_MENU_FONT;
        self.titleColor = [UIColor whiteColor];
        self.fontSize = MIN_MENU_FONT;
        self.isCenterShowItem = YES;
        self.isShowTitleBar = YES;
    }
    return self;
}

-(void)creationComplete{
    //初始化array
    _buttons = [NSMutableArray array];
    //scrollView
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [_scrollView setShowsHorizontalScrollIndicator:NO];
    _scrollView.backgroundColor = self.backgroundColor;
    [self addSubview:_scrollView];
    [_scrollView setContentSize:CGSizeMake(MENU_BUTTON_WIDTH * [_items count], self.frame.size.height)];
    
    //遍历Items，生成button 添加到scrollView
    NSInteger itemCount = _items.count;
    //button间隔距离
    CGFloat cap = (_scrollView.frame.size.width-MENU_BUTTON_WIDTH*itemCount) / (itemCount+1);
    
    for (NSUInteger i=0; i<itemCount; i++) {
        StubObject *stub = [_items objectAtIndex:i];
        EFTagButton *button = [EFTagButton buttonWithType:UIButtonTypeCustom];
        button.stub = stub;
        CGFloat buttonWidth = MENU_BUTTON_WIDTH;
        [button setFrame:CGRectMake(MENU_BUTTON_WIDTH * i, 0, buttonWidth, self.frame.size.height)];
        [button setTitle:[stub getCaption] forState:UIControlStateNormal];
        [button setTitleColor:self.titleColor forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:_fontSize];
        button.tag = i;
        [button setBackgroundColor:[UIColor clearColor]];
        [button addTarget:self action:@selector(actionbtn:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:button];
        [_buttons addObject:button];
        
        //获取文字的size，根据文字的size固定tagview的位置
        CGSize size = [button.titleLabel.text sizeWithFont:[UIFont boldSystemFontOfSize:_selectedFontSize] constrainedToSize:CGSizeMake(button.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
        TagView *v = [[TagView alloc]initWithFrame:CGRectMake(button.frame.size.width-(button.frame.size.width-size.width)/2, -2, 21, 21)];
        [button addSubview:v];
        button.tagView = v;
        button.isShow = NO;
        if (itemCount>1) {
            button.isShow = YES;
            [self chatAddressBookAction];
            button.tagView.badgeValue = [self unreadCountWithStubobject:stub];
            //将关联apply的cell添加到EFMessageService的ViewMap中
            if ([stub getStringForKey:@"applyId" withDefaultValue:nil]) {
                NSMutableArray *sonArray = [[NSMutableArray alloc]init];
                if ([[EFMessageService sharedMessageService].viewMap objectForKey:[stub getStringForKey:@"applyId" withDefaultValue:nil]]) {
                    sonArray = [[EFMessageService sharedMessageService].viewMap objectForKey:[stub getStringForKey:@"applyId" withDefaultValue:nil]];
                }
                [sonArray addObject:button];
                [[EFMessageService sharedMessageService].viewMap setObject:sonArray forKey:[stub getStringForKey:@"applyId" withDefaultValue:nil]];
            }
        }
    }
    
    //居中显示
    [self centerShowItems];
    //导航条
    if (self.isShowTitleBar) {
        UIButton *button = [_buttons objectAtIndex:0];
        //计算UILabel中字的size
        CGSize size = [button.titleLabel.text sizeWithFont:[UIFont boldSystemFontOfSize:_selectedFontSize] constrainedToSize:CGSizeMake(button.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
        _titleBar = [[UIView alloc] initWithFrame:CGRectMake(button.frame.origin.x + (button.frame.size.width - size.width)/2, button.frame.size.height - 2, size.width, 2)];
        _titleBar.backgroundColor = _selectedTitleColor;
        [_scrollView addSubview:_titleBar];
    }
    [self selectMenuAtIndex:0];
}

-(NSString *)unreadCountWithStubobject:(StubObject *)stub {
    //XML上配置的一些APPLYID总共的未读数目
    NSArray  *appArray = [[stub getStringForKey:@"applyId" withDefaultValue:nil] componentsSeparatedByString:@";"];
    NSInteger applyCount = 0;
    if (appArray) {
        //根据EFMessageService的menuMap 赋值badgevalue
        for (NSString *applyID in appArray) {
            applyCount += [[[EFMessageService sharedMessageService].menuMap objectForKey:applyID] integerValue];
        }
    }
    //特殊处理的一些未读数目
    NSInteger listCount = 0;
    if ([[stub.stubTable objectForKey:@"show"] isEqualToString:@"EFChatListViewController"]) {
        //是聊天列表
        listCount = [[EnvironmentVariable getPropertyForKey:@"EFChatListViewController" WithDefaultValue:@"0"] integerValue];
        
        if ((listCount + applyCount)>99) {
            return @"99+";
        }
        return [NSString stringWithFormat:@"%ld",listCount+applyCount];
        
    }else if([[stub.stubTable objectForKey:@"show"] isEqualToString:@"EFTaskListViewController"]){
        listCount = [[EnvironmentVariable getPropertyForKey:@"EFTaskListViewController" WithDefaultValue:@"0"] integerValue];
        
        if ((listCount + applyCount)>99) {
            return @"99+";
        }
        return [NSString stringWithFormat:@"%ld",listCount+applyCount];
    }else {
        return [NSString stringWithFormat:@"%ld",applyCount];
    }
    return @"0";
}

//是否应用号消息
- (BOOL)isApplyAction:(NSString *)userIdStr{
    if ([[EFMessageService sharedMessageService].menuMap objectForKey:userIdStr]) {
        return YES;
    }
    return NO;
}

-(void)unreadcountRefresh:(NSNotification *)note {
    NSMutableArray *chatListArray = [[NSMutableArray alloc]init];
    chatListArray  = [EFMessageService sharedMessageService].listArray;
    NSInteger badgeValue = 0;
    for (EFChatListModel *model in chatListArray) {
        BOOL isBother = model.isBother;
        if (!isBother) {
            BOOL isApply = [self isApplyAction:[NSString stringWithFormat:@"%d",model.message.fromUserID]];
            if (!isApply) {
                badgeValue = badgeValue + [[JFMessageManager sharedMessageManager] unreadCountWithUserID:model.userId postType:[model.type integerValue]];
                [model.badgerNum integerValue];
            }
        }
    }
    [EnvironmentVariable setProperty:[NSString stringWithFormat:@"%ld",badgeValue] forKey:@"EFChatListViewController"];
    for (EFTagButton *item in _buttons) {
        if (item.isShow) {
            NSString *showName = [item.stub getStringForKey:@"show" withDefaultValue:nil];
            if ([showName isEqualToString:note.object]) {
                if ([[EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"] integerValue]>99) {
                    item.tagView.badgeValue = @"99+";
                }else {
                    item.tagView.badgeValue = [EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"];
                }
            }
        }
    }
}

-(void)chatAddressBookAction{
    NSString *NewFr = [EnvironmentVariable getPropertyForKey:@"newFriendBadgeValue" WithDefaultValue:@"0"];
    NSString *NewJoin = [EnvironmentVariable getPropertyForKey:@"newJoinGroupBadgeValue" WithDefaultValue:@"0"];
    NSInteger N = [NewFr integerValue] + [NewJoin integerValue];
    for (EFTagButton *item in _buttons) {
        NSString *showName = [item.stub getStringForKey:@"show" withDefaultValue:nil];
        if ([showName isEqualToString:@"ChatAddressBookViewController"]) {
            item.tagView.badgeValue = [NSString stringWithFormat:@"%ld",N];
        }
    }
}

-(void)taskUnreadRefresh:(NSNotification *)note {
    for (EFTagButton *item in _buttons) {
        NSString *showName = [item.stub getStringForKey:@"show" withDefaultValue:nil];
        if ([showName isEqualToString:note.object]) {
            if ([[EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"] integerValue]>99) {
                item.tagView.badgeValue = @"99+";
            }else {
                item.tagView.badgeValue = [EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"];
            }
            
        }
    }
}

#pragma -mark -判断scrollMenu是否布满屏幕，如果不能布满，判断是否居中显示

-(void)centerShowItems{
    CGFloat scrollViewWidth = _scrollView.frame.size.width;
    if (self.isCenterShowItem && scrollViewWidth > _scrollView.contentSize.width) {
        CGFloat scrollWidth = scrollViewWidth/[_buttons count];
        for (NSUInteger i = 0; i < _buttons.count; i++ ) {
            EFTagButton *button = [_buttons objectAtIndex:i];
            CGRect frame = button.frame;
            frame.origin.x = i * scrollWidth;
            frame.size.width = scrollWidth;
            button.frame = frame;
            CGSize size = [button.titleLabel.text sizeWithFont:[UIFont boldSystemFontOfSize:_selectedFontSize] constrainedToSize:CGSizeMake(button.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
            button.tagView.frame = CGRectMake(button.frame.size.width-(button.frame.size.width-size.width)/2, -2, 21, 21);
        }
    }else {
        for (NSUInteger i = 0; i < _buttons.count; i++ ) {
            EFTagButton *button = [_buttons objectAtIndex:i];
            CGSize size = [button.titleLabel.text sizeWithFont:[UIFont boldSystemFontOfSize:_selectedFontSize] constrainedToSize:CGSizeMake(button.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
            button.tagView.frame = CGRectMake(button.frame.size.width-(button.frame.size.width-size.width)/2, -2, 21, 21);
        }
    }
    
}

-(void)resetViewItems:(NSMutableArray *)items{
    [[[self subviews] objectAtIndex:0] removeFromSuperview];
    self.items = items;
    [self creationComplete];
}

- (void)actionbtn:(UIButton *)button {
    [self changeButtonState:button];
    
    //调用delegate
    if (_delegate!= nil && [_delegate respondsToSelector:@selector(menu:didClickItem:position:)]) {
        [_delegate menu:self didClickItem:[_items objectAtIndex:button.tag] position:(int)button.tag];
    }
}

-(void)changeButtonState:(UIButton *)button{
    if (_currentSelectedButton == button) {
        return;
    }
    CGFloat xx = (button.tag -1) * MENU_BUTTON_WIDTH;
    [_scrollView scrollRectToVisible:CGRectMake(xx, 0, _scrollView.frame.size.width, _scrollView.frame.size.height) animated:YES];
    //变红变大
    [button setTitleColor:_selectedTitleColor forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:_selectedFontSize];
    //    [button setBackgroundColor:[UIColor cyanColor]];
    //变黑变小
    _currentSelectedButton.titleLabel.font = [UIFont systemFontOfSize:_fontSize];
    [_currentSelectedButton setTitleColor:_titleColor forState:UIControlStateNormal];
    //    [_currentSelectedButton setBackgroundColor:[UIColor whiteColor]];
    _currentSelectedButton = button;
    
    //计算UILabel中字的size
    CGSize size = [button.titleLabel.text sizeWithFont:button.titleLabel.font constrainedToSize:CGSizeMake(button.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
    
    //导航条
    //偏移动画
    [UIView beginAnimations:@"move" context:nil];
    [UIView setAnimationDuration:0.3];
    
    //    [UIView setAnimationDelegate:self];
    //改变它的frame的x的值 和 宽度
    if (_titleBar != nil) {
        CGRect bFrame = _titleBar.frame;
        bFrame.origin.x = button.frame.origin.x + (button.frame.size.width - size.width)/2;
        bFrame.size.width = size.width;
        _titleBar.frame = bFrame;
    }
    [UIView commitAnimations];
}

#pragma mark - 选中按钮
-(void)selectMenuAtIndex:(int)index {
    UIButton *button = [_buttons objectAtIndex:index];
    [self changeButtonState:button];
}

#pragma mark - 添加条目
-(void) addItemForArray:(StubObject *)item{
    [_items addObject:item];
}

@end

